﻿using Autofac;
using Autofac.Core;
using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.Runtime.Loader;
using System.Text;
using System.Linq;
using System.Reflection;

namespace Framework.Domain.Interface.Factorys
{
    public class ExampleFactory
    {
        private static IContainer Container { get; set; }
        static ExampleFactory()
        {
            var builder = new ContainerBuilder();
            /////扫描所有的程序集
            //List<CompilationLibrary> compilationLibrary = DependencyContext
            //        .Default
            //        .CompileLibraries
            //        .Where(x => !x.Serviceable && x.Type != "package").ToList();


            List<string> dllList = new List<string>()
            {
                "Framework.Commons",
                "Framework.Domain",
                "Framework.Domain.Interface",
                "Application.Services",
                "Application.Services.Dto",
                "Application.Services.Interface",
                "Domain.Interface",
                "Domain.Organization",
                "Repository.Interface",
                "Repository.Organization",
            };

            foreach (var _compilation in dllList)
            {
                string assemblyPath = AppContext.BaseDirectory + _compilation + ".dll";
                Assembly list = AssemblyLoadContext.Default
                    .LoadFromAssemblyPath(assemblyPath);
                    //.LoadFromAssemblyName(new AssemblyName(_compilation));

                //注册程序集中满足条件的所有类型
                builder.RegisterAssemblyTypes(list)
                      .Where(t => (t.Name.EndsWith("AppServices") || t.Name.EndsWith("Domain") || t.Name.EndsWith("Repository")) && !t.IsAbstract)
                      .AsImplementedInterfaces()
                      .PropertiesAutowired();

            }

            Container = builder.Build();
        }

        public static T CreateAppService<T>(params Parameter[] parameters)
        {
            var scope = Container.BeginLifetimeScope();
            return scope.Resolve<T>(parameters);
        }
    }
}
